package com.beichen.controller;

import com.beichen.pojo.CertificateInfo;
import com.beichen.service.CertificateService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class CertificateController {

    private final CertificateService certificateService;

    public CertificateController(CertificateService certificateService) {
        this.certificateService = certificateService;
    }

    @PostMapping("/recognize-certificate")
    public ResponseEntity<CertificateInfo> recognizeCertificate(@RequestParam("file") MultipartFile file) {
        try {
            File tempFile = saveFileToTemp(file);
            String filePath = tempFile.getAbsolutePath();

            // 直接使用文件路径，不再添加file://前缀
            CertificateInfo result = certificateService.recognize(filePath);

            // 返回结果对象，Spring 会自动将其转换为 JSON
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private File saveFileToTemp(MultipartFile file) throws IOException {
        // 保留原始文件名
        String originalFilename = file.getOriginalFilename();
        String extension = getFileExtension(originalFilename);

        File tempFile = File.createTempFile("certificate_", "." + extension);
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(file.getBytes());
        }
        return tempFile;
    }

    private String getFileExtension(String filename) {
        if (filename == null || filename.isEmpty()) {
            return "tmp";
        }
        int dotIndex = filename.lastIndexOf('.');
        return (dotIndex == -1) ? "tmp" : filename.substring(dotIndex + 1);
    }
}